package com.bestom.videoplay.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.view.SurfaceHolder;
import android.widget.MediaController;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bestom.videoplay.MediaApplication;
import com.bestom.videoplay.service.VideoPlayService;
import com.bestom.videoplay.listener.MediaPlayerListener;


public class VideoPlayService extends Service implements MediaController.MediaPlayerControl{

    private MediaPlayerListener mediaPlayerListener = new MediaPlayerListener();

    private MediaPlayer mediaPlayer = MediaApplication.getApplication().getMediaPlayer();

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) mediaPlayer.release();
    }

    @Override
    public void start() {
        if (null != mediaPlayer) {
            mediaPlayer.start();
        }
    }

    @Override
    public void pause() {
        if (null != mediaPlayer) {
            mediaPlayer.pause();
        }
    }

    @Override
    public int getDuration() {
        return mediaPlayer.getDuration();
    }

    @Override
    public int getCurrentPosition() {
        return mediaPlayer.getCurrentPosition();
    }

    @Override
    public void seekTo(int i) {
        mediaPlayer.seekTo(i);
    }

    @Override
    public boolean isPlaying() {
        return mediaPlayer.isPlaying();
    }

    @Override
    public int getBufferPercentage() {
        return mediaPlayerListener.getBufferPercentage();
    }

    @Override
    public boolean canPause() {
        return true;
    }

    @Override
    public boolean canSeekBackward() {
        return true;
    }

    @Override
    public boolean canSeekForward() {
        return true;
    }

    @Override
    public int getAudioSessionId() {
        return 0;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new VideoPlayService.MediaControlBinder();
    }

    public class MediaControlBinder extends Binder {
        public VideoPlayService getService() {
            return VideoPlayService.this;
        }

        public void startPlay(){
            start();
        }

        public void stopPlay(){
            pause();
        }
        public void setSeekTo(int i){
            seekTo(i);
        }
    }


}
